package com.myk.game.lib.views;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

/**
 * 数字倒计时控件
 */
public class CountDownTextView extends AppCompatTextView {

    private final Handler handler = new Handler(Looper.getMainLooper());
    private CountDownCallback callback;

    public CountDownTextView(Context context) {
        this(context,null);
    }

    public CountDownTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CountDownTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 开始倒计时
     */
    public void action(int num,@NonNull CountDownCallback c){
        this.callback = c;
        handler.post(new Runnable() {
            int time = num;
            @Override
            public void run() {
                if (time>0){
                    setText(""+time);
                    callback.onCount(false,time); //当前回调
                    time--;
                    handler.postDelayed(this,1000);
                }else {
                    callback.onCount(true,time); //结束回调
                    callback = null;
                    setVisibility(GONE);
                }
            }
        });
    }

    /**
     * 倒计时回调
     */
    public interface CountDownCallback{
        /**
         * @param isReach 是否结束
         * @param curNum 当前数值
         */
        void onCount(boolean isReach,int curNum);
    }


}
